/*
 * YACP
 * Systemnahe Programmierung
 * ITM 12 - Task 1
 *
 * yacp.c
 *
 * autor: David Rieger
 * version: 0.4
 * date: 30. Apr. 2014
 */

#include <stdio.h>
#include <string.h>
#include <errno.h>
#include <unistd.h>
#include <fcntl.h>

int main(int argc, char * argv[]) {

    /*Check number of params*/
    if (argc != 3) {
        fprintf(stderr,"yacp: parmeter error\nusage: ./yacp <source-file> <target-file>\n");
        return 1;
    }

    char * f_src_path = argv[1];
    char * f_des_path = argv[2];

    /* Create destination file with sc open
     * open with O_CREATE, so new file is being created
     * open with O_EXCL to ensure file isn't already existing
     */
    int dest_file_ret = open(f_des_path, O_WRONLY | O_CREAT | O_EXCL, 0666); 

    /* Handle errors for open */
    if (dest_file_ret < 0) {
        fprintf(stderr,"yacp: could not create file \"%s\"\n", f_des_path);
        fprintf(stderr,"%s\n", strerror(errno));      
        return errno;
    }

    /* Open source file */
    int src_file_ret = open(f_src_path, O_RDONLY);
    if (src_file_ret < 0) {
        fprintf(stderr,"yacp: could not read from file \"%s\"\n", f_src_path);
        fprintf(stderr,"%s\n", strerror(errno));
        remove(f_des_path);
        return errno;
    }

    char char_buffer[2048];
    /* Read from source file and write to destination file */
    int read_ret;
    int write_ret;
    do {
        /* READ */
        read_ret = read(src_file_ret, char_buffer, 2048);
        if (read_ret < 0) {
            fprintf(stderr,"yacp: error while reading from file\"%s\"\n", f_src_path);
            fprintf(stderr,"%s\n", strerror(errno));
            remove(f_des_path);
            return errno;
        }
        /* WRITE  // read_ret eq. size */ 
        write_ret = write(dest_file_ret, char_buffer, read_ret);
        if (write_ret < 0) {
            fprintf(stderr,"yacp: error while writing to file\"%s\"\n", f_des_path);
            fprintf(stderr,"%s\n", strerror(errno));
            remove(f_des_path);
            return errno;
        }
    } while (read_ret);
    return 0;
}
